package com.geomesa.spark.SparkJTS;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import org.geotools.geometry.jts.JTSFactoryFinder;

/**
 * 计算两点的距离，单位：米
 */
public class CalPointDistance {

    // 圆周率
    public static final double PI = 3.14159265358979324;
    // 赤道半径(单位m)
    private static final double R = 6378137;
    static GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);

    public static void main(String[] args) {

        Coordinate coordinate1 = new Coordinate(121.97738334, 37.47710858);
        Coordinate coordinate2 = new Coordinate(121.97738305, 37.47710848);
        Coordinate coordinate3 = new Coordinate(121.97728053, 37.47707084);
        Coordinate coordinate4 = new Coordinate(121.97634265, 37.47672591);
        Coordinate coordinate5 = new Coordinate(1.357846020181606E7, 4505819.87283728);
        Coordinate coordinate6 = new Coordinate(1.357846016964474E7, 4505819.85796843);
        Coordinate coordinate7 = new Coordinate(1.35784487570592E7, 4505814.57812586);
        Coordinate coordinate8 = new Coordinate(1.357806562654136E7, 4505636.46270748);
        //1.357806562654136E7,4505636.46270748
        Coordinate[] coordinates1 = new Coordinate[]{coordinate2, coordinate3, coordinate4};
        Coordinate[] coordinates2 = new Coordinate[]{coordinate6, coordinate7};

        Operation op = new Operation();
        double a = op.distanceGeo(geometryFactory.createPoint(coordinate1), geometryFactory.createPoint(coordinate2));
        double b = op.distanceGeo(geometryFactory.createPoint(coordinate1), geometryFactory.createLineString(coordinates1));
        double c = op.distanceGeo(geometryFactory.createPoint(coordinate5), geometryFactory.createPoint(coordinate8));
        double d = op.distanceGeo(geometryFactory.createPoint(coordinate5), geometryFactory.createLineString(coordinates2));
        System.out.println("点到点的距离：" + a + "点到线的距离：" + b);
        System.out.println("点到点的距离：" + c + "点到线的距离：" + d);

        System.out.println(getDistance(37.47710858, 121.97738334, 37.47710848, 121.97738305));
    }

    public static double getDistance(double lat1, double lng1, double lat2, double lng2) {
        double x, y, distance;
        x = (lng2 - lng1) * PI * R
                * Math.cos(((lat1 + lat2) / 2) * PI / 180) / 180;
        y = (lat2 - lat1) * PI * R / 180;
        distance = Math.hypot(x, y);
        //单位：米
        return distance;
    }
}
